//
//  YDBMineViewController.swift
//  DKE-Album
//
//  Created by 杨东宝 on 2018/8/8.
//  Copyright © 2018年 杨东宝. All rights reserved.
//

import UIKit

let  minIdentifier  = "MineHomCell";
let  minHeaderIdentifier = "MineHeaderIdentifier";

class YDBMineViewController: YDBBaseViewController {
    lazy var datasource: [[[String:String]]] = {
        let array = [[["title":"学习设置","clickSelector":"studaySettingClick","icon":"studaySetting"],
                      ["title":"错词本","clickSelector":"wrongWordClick","icon":"wrongWord"],
                      ["title":"我的收藏","clickSelector":"collectionClick","icon":"collection"],
                      ["title":"学习档案","clickSelector":"learningFilesClick","icon":"learningFiles"],
                      ["title":"消息中心","clickSelector":"messageCenterClick","icon":"messageCenter"],
                      ["title":"我的订单","clickSelector":"myOrderClick","icon":"myOrder"],
                      ["title":"我的卡券","clickSelector":"myCardClick","icon":"myCard"]],
                     [["title":"推荐有礼","clickSelector":"recommendClick","icon":"recommend"],
                      ["title":"常见问题","clickSelector":"QAClick","icon":"QA"],
                      ["title":"意见反馈","clickSelector":"feedbackClick","icon":"feedback"],
                      ["title":"联系客服","clickSelector":"contactClick","icon":"contact"],
                      ["title":"关于我们","clickSelector":"aboutUsClick","icon":"aboutUs"],
                      ["title":"系统设置","clickSelector":"settingsClick","icon":"settings"]]]
        return array
    }()
    // MARK:-懒加载cllection
    private   lazy var  collectionView:UICollectionView = {
        var cellw:CGFloat = (kScreenWidth - DIMENSION_VALUE(46)) / 4
        var cellh:CGFloat = DIMENSION_VALUE(82)
        var flowLayout = JJCollectionViewRoundFlowLayout_Swift()
        flowLayout.headerReferenceSize = CGSize(width: kScreenWidth, height: DIMENSION_VALUE(10))
        flowLayout.sectionInset            = UIEdgeInsets(top: DIMENSION_VALUE(14), left: DIMENSION_VALUE(8), bottom: DIMENSION_VALUE(14), right: DIMENSION_VALUE(8));
        flowLayout.minimumInteritemSpacing = -1;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.itemSize = CGSize(width:cellw,height:cellh)
        var collectionViewY = self.headerView.frame.maxY
        var collectionViewH = kScreenHeight - collectionViewY - kTabBarHeight
        
        let collection = UICollectionView.init(frame: CGRect(x: DIMENSION_VALUE(15), y: collectionViewY, width: kScreenWidth - DIMENSION_VALUE(30), height: collectionViewH), collectionViewLayout: flowLayout)
        collection.dataSource                     = self;
        collection.delegate                       = self;
        collection.showsVerticalScrollIndicator   = false;
        collection.showsHorizontalScrollIndicator = false;
        collection.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: minHeaderIdentifier)
        collection.register(MineHomCell.self, forCellWithReuseIdentifier: minIdentifier)
        collection.backgroundColor = UIColor.clear
        return collection
    }()
    // MARK:-懒加载头部视图
    private  lazy var headerView:MineHeaderView = {
        let week = MineHeaderView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: DIMENSION_VALUE(133) + kTopHeight))
        return week
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "我的"
        view.addSubview(headerView)
        view.addSubview(collectionView)
        
        NotificationCenter.default.addObserver(self, selector:  #selector(loginSuccess), name:loginSuc, object: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        headerView.setusermodel(model: userManger.curUserInfo)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 跳转页面的导航 不隐藏 false
        self.navigationController?.setNavigationBarHidden(false, animated: false)
    }
    @objc func loginSuccess() {
        headerView.setusermodel(model: userManger.curUserInfo)
    }
}
//MARK:- UICollectionViewDelegate, UICollectionViewDataSource
extension YDBMineViewController:UICollectionViewDelegate, UICollectionViewDataSource{
    func numberOfSections(in collectionView: UICollectionView) -> Int {datasource.count}
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {datasource[section].count}
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: minIdentifier, for: indexPath) as! MineHomCell
        let dict = datasource[indexPath.section][indexPath.row]
        cell.setDict(dict: dict)
        return cell;
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) ->
        UICollectionReusableView {
            if kind  ==  UICollectionView.elementKindSectionHeader {
                let  heardView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: minHeaderIdentifier, for: indexPath)
                heardView.backgroundColor = UIColor.clear
                return heardView;
            }
            return UICollectionReusableView();
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let dict = datasource[indexPath.section][indexPath.row]
        let selectorStr = dict["clickSelector"];
        
        if selectorStr  != "contactClick" && selectorStr  != "aboutUsClick" {
            if !userManger.isLogined {
                return
            }
        }
        if ((selectorStr != nil) && ((selectorStr?.count) != nil)) {
            let  selector:Selector = NSSelectorFromString(selectorStr ?? "");
            if (self.responds(to: selector)) {
                self.perform(selector)
            }
        }
    }
}
//MARK:-点击方法
extension YDBMineViewController{
    // MARK: - 跳转方法

    // MARK: 常见问题
    @objc func QAClick() {
        let webVC = QAWebViewController.init(with: "https://api.kytingting.com/common_questions.html", navigType: .navbar)
        self.navigationController?.pushViewController(webVC, animated: true)
        DebugLog("QAClick")
    }

    // MARK: 联系客服
    @objc func contactClick() {
        self.getServicePhone()
        DebugLog("contactClick")
    }
    // MARK: 关于我们
    @objc func aboutUsClick() {
        let webVC = BaseWebViewController.init(with: "https://api.kytingting.com/aboutus.html", navigType: .navbar)
        self.navigationController?.pushViewController(webVC, animated: true)
        DebugLog("aboutUsClick")
    }
    // MARK: 系统设置
    @objc func settingsClick() {  
        DebugLog("settingsClick")
        navigationController?.pushViewController(MineSettingVC(), animated: true)
    }
}
//MARK:-设置section圆角以及背景色
extension YDBMineViewController:JJCollectionViewDelegateRoundFlowLayout_Swift{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        let model = JJCollectionViewRoundConfigModel_Swift.init();
        model.backgroundColor = HexRGB(0xffffff)
        model.cornerRadius = DIMENSION_VALUE(2.5);
        return model;
    }
    
}
extension YDBMineViewController{
    
    //获取客服电话
    func getServicePhone() {
        self.callPhone(phone: "123456789")
//        NetWorkRequest(UserAPI.userGetCustomerServicePhone, completion: {[weak self](json) in
//            let phone = (JSON(json)["phone"].description)
//            self?.callPhone(phone: phone)
//        }) { (msg) in
//            YDBProgressHUD.showError(msg)
//        }
    }
    //打电话
    func callPhone(phone:String) {
        let diaLog =  AlertManger.alterDoubleCenterView(title: "", subTitle: "客服热线", okTitle: "呼叫", cancelTitle: "取消")
        diaLog.wEventOKFinish = {
            (anyID,otherData) in
            UIApplication.shared.openURL(URL(string :"tel://"+"\(phone)")!)
        }
        diaLog.wEventCancelFinish = {
            (anyID,otherData) in
        }
        let _ =  diaLog.wStart()
    }
}
